import logging
import os
import mimetypes

import webapp2

import settings
from data import json_response

mimetypes.add_type("image/svg+xml", ".svg")
mimetypes.add_type("application/json", ".json")

def template_server(request, path):
  # Check if the request is being made my Angular. If not then return the index file.
  x_requested_with = request.headers.get('X-Requested-With', None)
  if not x_requested_with or (x_requested_with != 'XMLHttpRequest'):
    return file_response(os.path.join(settings.PROJECT_DIR, 'main.html'))

  page_file = '%s.html' % path[:-1]
  page_file_path = os.path.join(settings.WWW_DIR, page_file)
  page_file_exists = file_exists(page_file_path)

  index_file = '%sindex.html' % path
  index_file_path = os.path.join(settings.WWW_DIR, index_file)
  index_file_exists = file_exists(index_file_path)

  if page_file_exists and index_file_exists:
    error_path = '/%s' % path
    error_page = os.path.join('/www/', page_file)
    error_index = os.path.join('/www/', index_file)
    error_msg = 'For the URL %s, found both %s and %s. You can\'t have both, so delete one or the other.' % (error_path, error_page, error_index)
    return webapp2.Response(error_msg, status_int=409)
  elif page_file_exists:
    return file_response(page_file_path)
  elif index_file_exists:
    return file_response(index_file_path)

  error_page = os.path.join('/www/', page_file)
  error_index = os.path.join('/www/', index_file)
  return webapp2.Response('Template does not exist. Searched for %s or %s' % (error_page, error_index), status_int=404)

def file_server(request, path):
  if path == '':
    return file_response(os.path.join(settings.PROJECT_DIR, 'main.html'))

  # Check user isn't putting template files directly in hrefs
  if path[-1] == '/':
    file_name = path.split(".")[0]
    error_msg = 'Invalid request. When linking to pages you can not use the file directly. Try: /%s/' % file_name
    return webapp2.Response(error_msg, status_int=404)
    
  file_path = os.path.join(settings.WWW_DIR, path)

  if file_exists(file_path):
    return file_response(file_path)
  else:
    error_path = os.path.join('/www/', path)
    return webapp2.Response('File could not be found. Searched for: %s' % error_path, status_int=404)

def json_file_server(request, path):
  file_path = os.path.join(settings.DATA_DIR, path)
  
  if file_exists(file_path):
    return file_response(file_path)
  else:
    return webapp2.Response('File could not be found.', status_int=404)

def file_exists(file_path):
  file_exists = False
  if os.path.exists(file_path):
    file_exists = True
  return file_exists

def file_response(file_path):
  f = open(file_path, 'r')
  response = webapp2.Response()
  response.headers['Content-Type'] = mimetypes.guess_type(file_path)[0]
  response.out.write(f.read())
  f.close()
  return response

def fake_template_file(request):
  return webapp2.Response('<blank></blank>')

application = webapp2.WSGIApplication([
  (r'/server/router\.html$', fake_template_file),
  (r'/data/$', json_response),
  (r'/data/([^.]+\/)$', json_response),
  (r'/data/(.*)$', json_file_server),
  # (r'/([^.]+\/)$', template_server), # Ref: Requires all URLs end in /
  (r'/([a-zA-Z0-9_\/\-]+)$', template_server),
  (r'/(.*)$', file_server),
], debug=True)
